package cn.shengchao.examstar.ai.acl.adapters.client;

import cn.shengchao.examstar.ai.acl.ports.ISpecificationTypeService;
import cn.shengchao.examstar.product.acl.ports.repositories.ISpecificationTypeRepository;
import cn.shengchao.examstar.product.infrastructure.dao.po.TSpecificationType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 类目类型服务客户端
 * 用于获取类目信息，是防腐层的适配器实现
 */
@Component
@Slf4j
public class SpecificationTypeClient implements ISpecificationTypeService {
    
    @Autowired
    private ISpecificationTypeRepository specificationTypeRepository;
    
    @Override
    public Map<Long, String> getSpecificationTypeNames(Set<Long> specificationTypeIds) {
        if (specificationTypeIds == null || specificationTypeIds.isEmpty()) {
            log.warn("类目ID集合为空，返回空Map");
            return Collections.emptyMap();
        }
        
        try {
            // 将Set转换为List
            List<Long> idList = specificationTypeIds.stream().toList();
            
            // 调用产品模块的仓储接口批量获取类目信息
            List<TSpecificationType> specificationTypes = specificationTypeRepository.getSpecificationTypesByIdList(idList);
            
            // 转换为ID到名称的映射
            return specificationTypes.stream()
                    .collect(Collectors.toMap(
                            TSpecificationType::getId,
                            TSpecificationType::getName,
                            (name1, name2) -> name1 // 如果有重复键，保留第一个
                    ));
        } catch (Exception e) {
            log.error("批量获取类目名称失败", e);
            // 发生异常时返回空Map
            return Collections.emptyMap();
        }
    }
    
    @Override
    public String getSpecificationTypeName(Long specificationTypeId) {
        if (specificationTypeId == null) {
            log.warn("类目ID为空，返回默认名称");
            return "未知类目";
        }
        
        try {
            // 调用批量方法
            Map<Long, String> nameMap = getSpecificationTypeNames(Set.of(specificationTypeId));
            return nameMap.getOrDefault(specificationTypeId, "未知类目");
        } catch (Exception e) {
            log.error("获取类目名称失败, specificationTypeId={}", specificationTypeId, e);
            return "未知类目";
        }
    }
} 